import router from "./router";
import pinia from "./store";
import {cookie} from "./utils/cookie";
import systemStore from "./store/modules/system/system";
import useUserStore from "@/store/modules/user/user";
//@ts-ignore
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import {RouteLocationNormalized, RouteRecordRaw} from "vue-router";


let systemstore = systemStore(pinia)
let userStore = useUserStore(pinia)
let token: {
    name: string,
    value: string
}

const channgeTabar = (to: RouteLocationNormalized) => {
    if (systemstore.tabbarRoutes.length == 0) {
        if (!to.meta.hidden) {
            let curRoute = userStore.allRoutes.find((item) => {
                return item.path === to.path
            })
            // console.log(userStore.menuRoutes)
            if (curRoute) {
                systemstore.setTabbarRoutes(curRoute)
            }
        }

    }

}

router.beforeEach(async (to, from, next) => {
    let fromStr = window.localStorage.getItem('from')
    nprogress.start()
    token = cookie.getCookie('token')
    await userStore.userInfo()
    if (to.meta.check) {
        if (token) {
            next()
            channgeTabar(to)
        } else {
            next(`/login?redirect=${to.path}`)
        }
    } else {
        next()
    }
    // console.log(token)
    // if (to.meta.check) {
    //     // console.log(to,token)
    //     if (token) {
    //         if (userStore.username) {
    //             //放行
    //             // console.log('放行')
    //             channgeTabar(to)
    //             next()
    //         } else {
    //             //如果没有用户信息,在守卫这里发请求获取到了用户信息再放行
    //             try {
    //                 //获取用户信息
    //                 await userStore.userInfo()
    //                 //放行
    //                 //万一:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
    //                 channgeTabar(to)
    //                 // next({to})
    //                 next()
    //             } catch (error) {
    //                 //token过期:获取不到用户信息了
    //                 //用户手动修改本地存储token
    //                 //退出登录->用户相关的数据清空
    //                 // await userStore.userLogout()
    //                 // next({ path: '/login', query: { redirect: to.path } })
    //             }
    //         }
    //     } else {
    //         next(`/login?redirect=${to.path}`)
    //     }
    // } else {
    //     next()
    // }
})

router.afterEach((to, from, next) => {
    nprogress.done()
})
